<template>
  <div class="box-main">
    <div class="topHeaderCard">
      <a-button type="primary" @click="resetBack" :icon="h(ArrowLeftOutlined)" ghost>
        返回
      </a-button>
    </div>
    <div class="bax-main-content">
      <div class="page-content">
        <div class="articles-box">
          <div class="title-box">
            <div class="title-item-left">
              <span class="text-icon" />
              {{ formData.id ? '编辑文章' : '新增文章' }}
            </div>
          </div>
          <div class="articles-content-box">
            <a-form :model="formData" :rules="rules" ref="formRef">
              <a-form-item label="标题" name="title">
                <a-input
                  style="width: 100%"
                  v-model:value="formData.title"
                  placeholder="请输入标题"
                />
              </a-form-item>
              <a-form-item label="分类" name="categoryName">
                <a-select
                  v-model:value="formData.categoryName"
                  style="width: 100%"
                  :options="labelsDataWrap"
                  showSearch
                  allowClear
                  placeholder="请选择分类"
                  @change="handleChange"
                />
              </a-form-item>
              <a-form-item label="标签" name="labelCodes">
                <a-select
                  v-model:value="formData.labelCodes"
                  style="width: 100%"
                  mode="multiple"
                  :options="labelsDataTags"
                  showSearch
                  allowClear
                  placeholder="请选择标签"
                />
              </a-form-item>
              <a-form-item label="正文" name="content" :labelCol="{ span: 24 }">
                <div style="height: calc(100vh - 445px)">
                  <Editor ref="editorRef" />
                </div>
              </a-form-item>
              <a-form-item style="text-align: center">
                <a-button type="primary" ghost style="margin-right: 35px" @click="previewHandle">
                  预览
                </a-button>
                <a-button type="primary" html-type="submit" @click="sendArticles"> 发布 </a-button>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </div>
    </div>

    <!-- 预览 -->
    <a-modal
      v-model:open="previewVisible"
      title="预览"
      width="400px"
      :footer="null"
      :bodyStyle="{ height: '500px', overflow: 'hidden auto' }"
    >
      <div class="preview-box">
        <div class="preview-content" v-html="formData.content" />
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, h, nextTick } from 'vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import Editor from '@/views/editor/editor.vue'
import { addKnowledgeBase, getKnowledgeBaseDetail, getAllTags } from '@/api/knowledgeBase'
import message from 'ant-design-vue/es/message'
import Modal from 'ant-design-vue/es/modal'

const editorRef = ref()
const emit = defineEmits(['close'])
const rules = ref({
  title: [{ required: true, message: '请输入标题', trigger: 'blur', whitespace: true }],
  labelCodes: [{ required: true, message: '请选择标签', trigger: 'change' }],
  categoryName: [{ required: true, message: '请选择分类', trigger: 'change' }],
  content: [
    {
      required: true,
      trigger: 'blur',
      validator: (_rule: any) => {
        if (editorRef.value) {
          const editorHtml = editorRef.value.getContent()
          if (!editorHtml || editorHtml == '<p><br></p>') {
            return Promise.reject('请输入正文')
          } else {
            return Promise.resolve()
          }
        } else {
          return Promise.resolve()
        }
      }
    }
  ]
})
const formRef = ref()
const formData = reactive<any>({
  labelCodes: [],
  labelCode: '',
  categoryName: undefined,
  title: '',
  content: '',
  id: undefined
})

const previewVisible = ref(false)

const labelsData = ref([])
const labelsDataWrap = ref([])
const labelsDataTags = ref([])
const tagAllData = ref<any>([])
const init = async (data: any, labels: any) => {
  previewVisible.value = false
  labelsData.value = labels

  labelsDataWrap.value = labels

  const tagData = await getAllTags()
  tagAllData.value = tagData.data
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    if (data) {
      getKnowledgeBaseDetail({ id: data.id }).then((res) => {
        Object.assign(formData, res.data)
        formData.labelCodes = []
        if (formData.categoryName) {
          formData.labelCodes = formData.labelCode ? formData.labelCode.split(',') : []
          const someTypeData = tagAllData.value.filter((vo: any) => {
            return vo.remark == formData.categoryName
          })
          labelsDataTags.value = someTypeData.map((vo: any) => {
            return {
              label: vo.dictLabel,
              value: vo.dictLabel
            }
          })
        }
        if (editorRef.value) {
          editorRef.value.setContent(formData.content)
        }
      })
    } else {
      formData.id = undefined
    }
  })
}
const handleChange = (values: any) => {
  labelsDataTags.value = []
  formData.labelCodes = []
  const someTypeData = tagAllData.value.filter((vo: any) => {
    return vo.remark == values
  })
  labelsDataTags.value = someTypeData.map((vo: any) => {
    return {
      label: vo.dictLabel,
      value: vo.dictLabel
    }
  })
}
// 发布
const sendArticles = () => {
  formRef.value.validate().then(() => {
    Modal.confirm({
      title: '发布文章',
      content: '你确定发布文章吗？',
      okText: '发布',
      cancelText: '取消',
      onOk: () => {
        formData.labelCode = formData.labelCodes.join(',')
        // console.log(editorRef.value.getContent())formData.categoryName
        formData.content = editorRef.value.getContent()
        const data = JSON.parse(JSON.stringify(formData))
        delete data.creator
        delete data.labelCodes
        addKnowledgeBase(data)
          .then(() => {
            message.success('发布成功')
            resetBack()
          })
          .catch(() => {
            message.error('发布失败')
          })
      },
      onCancel: () => {
        console.log('取消')
      }
    })
  })
}

// 预览
const previewHandle = () => {
  if (editorRef.value && editorRef.value.getContent()) {
    previewVisible.value = true
    formData.content = editorRef.value.getContent()
  }
}

const resetBack = () => {
  emit('close')
}

defineExpose({
  init
})
</script>
<style lang="less" scoped>
.box-main {
  width: 100%;
  height: 100%;
  padding: 0 !important;
  overflow: hidden !important;

  .topHeaderCard {
    width: 100%;
    height: 48px;
    display: flex;
    align-items: center;
    background-color: #fff;
    padding-left: 24px;

    ::v-deep(.ant-tabs-nav) {
      margin: 0;
    }

    ::v-deep(.ant-tabs-nav-wrap) {
      padding: 0 20px;
      padding-top: 2px;
      height: 48px;
    }
  }

  .bax-main-content {
    width: 100%;
    height: calc(100% - 50px);
    overflow: hidden auto;
    padding: 16px;

    .page-content {
      height: 100%;
      width: 100%;
      display: flex;
    }

    .articles-box {
      width: 100%;
      height: 100%;
      background-color: #fff;
      padding: 16px;
    }

    .articles-content-box {
      padding-top: 6px;
      padding-right: 10px;
      width: 100%;
      height: calc(100% - 50px);
      overflow: hidden auto;
    }
  }
}

.title-box {
  width: 100%;
  height: 32px;
  color: #1d2129;
  line-height: 32px;
  font-weight: 600;
  margin: 0 0 10px;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;

  .title-item-left {
    font-weight: 600;
    font-size: 18px;
    display: flex;
    align-items: center;
  }

  .text-icon {
    width: 3px;
    height: 16px;
    background: #165dff;
    margin-right: 8px;
    display: inline-block;
    line-height: 32px;
  }
}
</style>
<style>
.preview-content img {
  max-width: 100%;
}

.preview-content p {
  margin-bottom: 5px;
}
</style>
